package com.kkwrite.regimen.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by lisha on 2018/8/15 20:58.
 *
 * @author lisha
 */
@Component
public class ShopApiAccessPreFilter extends ZuulFilter {

    private final Logger logger = LoggerFactory.getLogger(ShopApiAccessPreFilter.class);
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    /**
     * pre：可以在请求被路由之前调用
     * routing：在路由请求时候被调用
     * post：在routing和error过滤器之后被调用
     * error：处理请求时发生错误时被调用
     *
     * @return string
     */
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        if (uri.startsWith("/api/shop/")) {
            List<String> passableUri = Arrays.asList("/api/shop/login/adminlogin", "/api/shop/register");
            if (!passableUri.contains(uri) && !isSwaggerUIResource(uri)) {
                String token = request.getHeader("token");
                if (StringUtils.isBlank(token)) {
                    error(requestContext, "error", "token is empty");
                    return null;
                }
                if (isTokenInvalid(token)) {
                    error(requestContext, "002", "token invalid");
                }
            }
        }
        return null;
    }

    private void error(RequestContext requestContext, String message, String desc) {
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(401);
        Map<String, String> map = new HashMap<>(16);
        map.put("success", "false");
        map.put("msg", message);
        map.put("desc", desc);
        map.put("data", null);
        HttpServletResponse response = requestContext.getResponse();
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try (PrintWriter out = response.getWriter()) {
            out.write(JSON.toJSONString(map));
            out.flush();
        } catch (IOException e) {
            logger.error("写出错误信息异常，异常信息：" + e.getMessage(), e);
        }
    }

    private boolean isTokenInvalid(String token) {
        long expire;
        try {
            expire = redisTemplate.getExpire(token, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return true;
        }
        /// 小于10s认为token已失效，在业务逻辑处依然需要判断
        /// 尽量将token过期在filter拦截
        return expire <= 10;
    }

    private boolean isSwaggerUIResource(String uri) {
        return "/api/shop/swagger-ui.html".equals(uri) || uri.startsWith("/api/shop/webjars") || "/api/shop/swagger-resources".equals(uri)
                || "/api/shop/v2/api-docs".equals(uri) || uri.startsWith("/api/shop/configuration");
    }

}
